<template>
  <div class="tabs2">
    <el-form :model="loginForm" ref="form" :rules="rules" label-width="80px">
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model.number="loginForm.phone" class="code1"></el-input>
      </el-form-item>
      <el-form-item label="验证码:" prop="captcha">
        <el-input v-model="loginForm.captcha" class="code2"></el-input>
        <getCodeBtn :getCode="getPhoneCode"></getCodeBtn>
      </el-form-item>
      <div class="loginItem">
        <el-button class="login" @click="login">登录</el-button>
      </div>
      <p class="tips">提示: 验证码接口有问题，用扫码登录</p>
    </el-form>
  </div>
</template>
<script>
import getCodeBtn from './getCodeBtn.vue' //获取验证码按钮组件
import { getVerifyCode, login } from '@/api/login/login'
export default {
  data() {
    return {
      loginForm: {
        captcha: '',
        phone: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  components: {
    getCodeBtn
  },
  methods: {
    async getPhoneCode() {
      if (!this.loginForm.phone) {
        this.$refs['form'].validateField('phone') //点击获取验证码按钮只对手机号进行检测校验
        return false
      }
      const res = await getVerifyCode({ phone: this.loginForm.phone })
      return res.data.code === 200
    },
    login() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const res = await login(this.loginForm)
          if (res?.data.code === 200) {
            window.localStorage.setItem('userId', res.data.profile.userId)
            this.$emit('getUserInfo', res.data.profile)
            this.$message.success('登陆成功!')
            this.$store.commit('updataLoginState', true)
          }
        } else {
          return
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tabs2 {
  // input边框样式
  :deep(.el-input__inner) {
    height: 35px;
    border: 1px solid #999;
    transition: all 1s;
    border-radius: 5px;
    &:focus {
      border-color: #ec4141;
    }
  }
  // 输入框前的文字
  :deep(.el-form-item__label) {
    font-size: 16px;
    font-weight: 700;
  }
  .code1 {
    width: 280px;
  }
  .code2 {
    width: 100px;
    margin-right: 20px;
  }
  .el-button {
    width: 160px;
    color: #fff;
    background-color: #ec4141;
    border-radius: 5px;
    &:hover {
      background-color: #d93f3f;
    }
  }
  .loginItem {
    display: flex;
    justify-content: center;
    margin-bottom: 15px;
    .login {
      width: 265px;
    }
  }
  .tips {
    text-align: center;
    font-size: 16px;
  }
}
</style>
